package com.cm.order.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cm.order.entity.Cart;
import com.cm.order.entity.dto.CartKeyWordDTO;
import com.cm.order.feign.GoodsFeign;
import com.cm.order.mapper.CartMapper;
import com.cm.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @类 名:CartServiceImpl </br>
 * @描 述:<br>
 * @日 期:2020/9/25 16:46 </br>
 * @作 者:小兰同学</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private GoodsFeign goodsFeign;
    @Override
    public boolean insert(Cart cart) {
        if(cartMapper.insert(cart)>0)
            return true;
        return false;
    }

    @Override
    public boolean delete(Long id) {
        if(cartMapper.deleteById(id) > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean update(Cart cart) {
        if (cartMapper.updateById(cart) > 0){
            return true;
        }
        return false;
    }

    @Override
    public IPage<Cart> getCartList(CartKeyWordDTO cartKeyWordDTO) {
        Page<Cart> page = new Page<>();
        cartKeyWordDTO.setCurrentPage((cartKeyWordDTO.getCurrentPage()-1)*cartKeyWordDTO.getPageSize());
        List<Cart> cartList=cartMapper.getCartList(cartKeyWordDTO);
        page.setRecords(cartList);
        page.setCurrent(cartKeyWordDTO.getCurrentPage());
        page.setSize(cartKeyWordDTO.getPageSize());
        int count=cartMapper.getCartTotal(cartKeyWordDTO);
        page.setTotal(count);
        return page;
    }

    @Override
    public List<Map<String,Object>> getGoodsByUser(Long userId) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        List<Cart> cartList=cartMapper.selectList(queryWrapper);
        List<Map<String,Object>> goodsList=new ArrayList<>();
        for (Cart cart:cartList){
            Long goodsId=cart.getGoodsId();
            Map<String,Object> goods=(Map<String,Object>)goodsFeign.getGoodsById(goodsId).getData();
            goodsList.add(goods);
        }
        return goodsList;
    }

    @Override
    public boolean deleteByUG(Long userId, Long goodsId) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("goods_id",goodsId);
        if (cartMapper.delete(queryWrapper)>0)
            return true;
        return false;
    }

}
